package com.edroid.droidhelper.pc.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


/**
 * 
 * @author yichou 2015-1-7
 *
 */
public class HttpUtils {
	static final Logger log = Logger.create("HttpUtils");
	
	public static final String CHARSET = "UTF-8";
	public static final String USERAGENT = "edroid-platform-2015-1-7";

	public static HttpClient getHttpClient() {
//		HttpClientBuilder builder = HttpClientBuilder.create();
//		HttpClient httpClient = builder.build();
		HttpClient httpClient = new DefaultHttpClient();
		
		return httpClient;
	}
	
	public static String post(String uri, NameValuePair... params) throws Exception {
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for (NameValuePair p : params) {
			list.add(p);
		}

		HttpPost post = new HttpPost(uri);
		post.setEntity(new UrlEncodedFormEntity(list, CHARSET));

		return post(post);
	}
	
	public static String post(HttpPost post) throws Exception {
		HttpClient client = null;

		try {
			client = getHttpClient();
			HttpResponse rsp = client.execute(post);
			int code = rsp.getStatusLine().getStatusCode();

			if (code == HttpStatus.SC_OK) {
				HttpEntity entity = rsp.getEntity();
				String ret = EntityUtils.toString(entity, CHARSET);
				
				EntityUtils.consume(entity);
				
				return ret;
			} else {
				log.e("post: rsp status code error, code=" + code);
			}
		} finally {
			if (client != null) {
				client.getConnectionManager().shutdown();
//				((CloseableHttpClient)client).close();
			}
		}

		return null;
	}
}
